define([], function() {
  var Uri = function(url) {
    var self = this;
    self.uri = url || window.location.href;
    self._parse();
  };

  Uri.prototype = {
    _parse: function() {
      var self = this;
      var uri = self.uri;

      //锚点
      var sharpIdx = uri.indexOf('#');
      if (sharpIdx !== - 1) {
        self.anchor = uri.slice(sharpIdx + 1);
        uri = uri.slice(0, sharpIdx);
      }

      //参数
      var quetoIdx = uri.indexOf('?');
      self.param = {};

      if (quetoIdx !== - 1 && quetoIdx !== uri.length - 1) {
        self.host = uri.slice(0, quetoIdx);
        var query = uri.slice(quetoIdx + 1);
        query = query.split('&');

        for (var idx = 0; idx < query.length; idx++) {
          var chunk = query[idx];
          var kv = chunk.split('=');
          if (kv.length > 1) {
            self.param[kv[0]] = kv[1];
          } else {
            self.param[kv[0]] = '';
          }
        }
      } else {
        self.host = uri;
      }
    },
    getAnchor: function(){
      return this.anchor;
    },
    setAnchor: function(anchor){
      this.anchor = anchor;
    },
    getHost: function() {
      return this.host;
    },
    setHost: function(host) {
      this.host = host;
    },
    setParam: function(k, v) {
      this.param[k] = v;
    },
    getParam: function(k) {
      return this.param[k];
    },
    toString: function() {
      var newUri = this.host;
      if (this.param) {
        var firstP = true;
        for (var k in this.param) {
          if (firstP) {
            newUri += '?';
            firstP = false;
          } else {
            newUri += '&';
          }
          if (this.param[k] === '') {
            newUri += k;
          } else {
            newUri += k + '=' + this.param[k];
          }
        }
      }
      if(this.anchor){
        newUri += '#' + this.anchor;
      }
      return newUri;
    }
  };

  return Uri;
});

